{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Finance Functions for Python\n",
    "\n",
    "This is a list of common financial formulas converted into Python code for your use.\n",
    "\n",
    "- **GitHub Link:** https://github.com/areed1192/sigma_coding_youtube/tree/master/python/python-finance\n",
    "- **YouTube Channel:** https://www.youtube.com/channel/UCBsTB02yO0QGwtlfiv5m25Q"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Present Value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "161.50558288984578"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def present_value(future_value, discount_rate, periods):\n",
    "    '''\n",
    "    Summary: Given a future value cash flow, estimate the present value of that cash flow.\n",
    "    \n",
    "    PARA future_value: The future value cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int\n",
    "   \n",
    "    '''\n",
    "\n",
    "    return future_value / ( 1 + discount_rate) ** periods\n",
    "\n",
    "# EXAMPLE \n",
    "fut_val = 1000.0\n",
    "rate = 0.2\n",
    "per = 10\n",
    "\n",
    "present_value(fut_val, rate, per)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Future Value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6191.7364223999975"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def future_value(present_value, discount_rate, periods):\n",
    "    '''\n",
    "    Summary: Given a present value cash flow, estimate the future value of that cash flow.\n",
    "    \n",
    "    PARA present_value: The present value cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int\n",
    "\n",
    "    '''\n",
    "\n",
    "    return present_value * ( 1 + discount_rate) ** periods\n",
    "\n",
    "# EXAMPLE \n",
    "pres_val = 1000.0\n",
    "rate = 0.2\n",
    "per = 10\n",
    "\n",
    "future_value(pres_val, rate, per)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Net Present Value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "358.87345679012344"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def net_present_value(discount_rate, cashflows):\n",
    "    '''\n",
    "    Summary: Given a series of cash flows, calculate the net present value of those cash flows.\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA cashflows: A series of cash flows.\n",
    "    PARA type: list\n",
    "\n",
    "    '''    \n",
    "    \n",
    "    # initalize result\n",
    "    total_value = 0.0\n",
    "    \n",
    "    # loop through cashflows and calculate discounted value.\n",
    "    for index, cashflow in enumerate(cashflows):\n",
    "        total_value += cashflow / (1 + discount_rate)**index\n",
    "        \n",
    "    return total_value \n",
    "\n",
    "# EXAMPLE\n",
    "rate = 0.2\n",
    "cashflows = [100, 100, 100, 100, 100]\n",
    "\n",
    "net_present_value(rate, cashflows)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Present Value Perpetuity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def present_value_perpetuity(cashflow, discount_rate):\n",
    "    '''\n",
    "    Summary: Given a cash flow, calculate the present value in perpetuity.\n",
    "     \n",
    "    PARA cashflow: A single cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "\n",
    "    '''       \n",
    "    \n",
    "    return cashflow / discount_rate\n",
    "\n",
    "# EXAMPLE\n",
    "cf = 1000.0\n",
    "rate = 0.01\n",
    "\n",
    "present_value_perpetuity(cf, rate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Present Value Perpetuity Due"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def present_value_perpetuity_due(cashflow, discount_rate):\n",
    "    '''\n",
    "    Summary: Given a cash flow, calculate the present value in perpetuity due.\n",
    "     \n",
    "    PARA cashflow: A single cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "\n",
    "    '''       \n",
    "    \n",
    "    return cashflow / discount_rate * (1 + discount_rate)\n",
    "\n",
    "# EXAMPLE\n",
    "cf = 1000.0\n",
    "rate = 0.01\n",
    "\n",
    "present_value_perpetuity_due(cf, rate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Present Value Annunity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def present_value_annuity(cashflow, discount_rate, periods):\n",
    "    '''\n",
    "    Summary: Given a cash flow, calculate the present value of an annuity.\n",
    "     \n",
    "    PARA cashflow: A single cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int\n",
    "\n",
    "    '''       \n",
    "    return cashflow / discount_rate * (1 - 1 / ( 1 + discount_rate )** periods)\n",
    "\n",
    "# EXAMPLE\n",
    "cf = 1000.0\n",
    "rate = 0.01\n",
    "per = 10\n",
    "\n",
    "present_value_annuity(cf, rate, per)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Present Value Annuity Due"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9566.017576008691"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def present_value_annuity_due(cashflow, discount_rate, periods):\n",
    "    '''\n",
    "    Summary: Given a cash flow, calculate the present value of an annuity due.\n",
    "     \n",
    "    PARA cashflow: A single cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int\n",
    "    \n",
    "    '''   \n",
    "    \n",
    "    return cashflow / discount_rate * (1 - 1 / ( 1 + discount_rate )** periods) * (1 + discount_rate)\n",
    "\n",
    "# EXAMPLE\n",
    "cf = 1000.0\n",
    "rate = 0.01\n",
    "per = 10\n",
    "present_value_annuity_due(cf, rate, per)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Present Value Growing Annuity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3499.038461402657"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def present_value_growing_annuity(cashflow, discount_rate, periods, growth_rate):\n",
    "    '''\n",
    "    Summary: Given a cash flow, calculate the present value of a growing annuity. The assumption is that the \n",
    "             discount rate > growth rate, otherwise a negative value will be returned.\n",
    "     \n",
    "    PARA cashflow: A single cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int\n",
    "    \n",
    "    PARA growth_rate: The growth rate\n",
    "    PARA type: float\n",
    "\n",
    "    '''   \n",
    "    \n",
    "    return cashflow / discount_rate * (1 - (1 + growth_rate) ** periods / (1 + discount_rate) ** periods)\n",
    "\n",
    "# EXAMPLE\n",
    "cf = 1000.0\n",
    "rate = 0.05\n",
    "per = 10\n",
    "gr = 0.03\n",
    "                                       \n",
    "present_value_growing_annuity(cf, rate, per, gr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Future Value Annuity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10462.212541120452"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def future_value_annuity(cashflow, discount_rate, periods):\n",
    "    '''\n",
    "    Summary: Given a cash flow, calculate the future value of an annuity.\n",
    "     \n",
    "    PARA cashflow: A single cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int\n",
    "    \n",
    "    '''  \n",
    "    return cashflow / discount_rate * (( 1 + discount_rate )** periods - 1)\n",
    "\n",
    "# EXAMPLE\n",
    "cf = 1000.0\n",
    "rate = 0.01\n",
    "per = 10\n",
    "\n",
    "future_value_annuity(cf, rate, per)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Future Value Annuity Due"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10566.834666531657"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def future_value_annuity_due(cashflow, discount_rate, periods):\n",
    "    '''\n",
    "    Summary: Given a cash flow, calculate the future value of an annuity due.\n",
    "     \n",
    "    PARA cashflow: A single cash flow.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA discount_rate: The discount rate\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int\n",
    "\n",
    "    '''   \n",
    "    \n",
    "    return cashflow / discount_rate * (( 1 + discount_rate )** periods - 1) * (1 + discount_rate)\n",
    "\n",
    "# EXAMPLE\n",
    "cf = 1000.0\n",
    "rate = 0.01\n",
    "per = 10\n",
    "\n",
    "future_value_annuity_due(cf, rate, per)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Effective Annual Rate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.030408257071388167"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def eff_annual_rate(apr, frequency):\n",
    "    '''\n",
    "    Summary: Given an APR (Annual Percentage Rate) calculate the EAR (Effective Annual Rate)\n",
    "     \n",
    "    PARA apr: The Annual Percentage Rate.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA frequency: The compounding frequency.\n",
    "    PARA type: int\n",
    "    '''\n",
    "    \n",
    "    return (1 + apr / frequency) ** frequency - 1\n",
    "\n",
    "# EXAMPLE\n",
    "annual_rate = .03\n",
    "comp_freq = 10\n",
    "\n",
    "eff_annual_rate(annual_rate, comp_freq)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Stock Valuation Model - n Periods"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "27.580917797677404"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def stock_valuation_n_period(discount_rate ,LT_growth_rate, dividends):\n",
    "    \"\"\"\n",
    "    Summary: Given an array of dividends, estimate the stock price using an n-period model.\n",
    "    \n",
    "    PARA discount_rate: The discount rate used to calculate the NPV & PV calculations\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA LT_growth_rate: The long-term growth rate used to calculate the last dividend in perpetuity.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA dividends: A list of dividends where the last dividend is the one that is paid in perpetuity.\n",
    "    PARA type: float\n",
    "    \n",
    "    \"\"\"\n",
    "    \n",
    "    # get the dividend array & the last dividend\n",
    "    div_array = dividends[:-1]\n",
    "    div_last = dividends[-1]\n",
    "    \n",
    "    # define the number of periods.\n",
    "    num_pers = len(dividends) - 1\n",
    "\n",
    "    # calculate the present value of the dividends.\n",
    "    pres_val = net_present_value(discount_rate, div_array) * (1 + discount_rate)\n",
    "\n",
    "    # calculate late the terminal value, which is a dividend in perpituity.\n",
    "    last_div_n = div_last / (discount_rate - LT_growth_rate)    \n",
    "\n",
    "    # calulate the the total value which is the pv of the dividends cashflow \n",
    "    # and the present value of the dividend in perpituity.\n",
    "    total_val = pres_val + present_value(last_div_n, discount_rate, num_pers)\n",
    "    \n",
    "    return total_val\n",
    "    \n",
    "\n",
    "#EXAMPLE\n",
    "disc_rate = 0.12\n",
    "grow_rate = 0.03\n",
    "dividends = [1.8, 2.07, 2.277, 2.48193, 2.68, 2.7877]\n",
    "\n",
    "stock_valuation_n_period(disc_rate, grow_rate, dividends)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dividend Discount Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11.609142911150624"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def divident_discount_model(discount_rate, dividends, growth_rate, stock_price, periods):\n",
    "    \"\"\"\n",
    "    Summary: Given an array of dividends, estimate the stock price using an n-period model.\n",
    "    \n",
    "    PARA discount_rate: The discount rate used to calculate the NPV & PV calculations.\n",
    "    PARA type: float\n",
    "\n",
    "    PARA dividends: The period 0 dividend.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA growth_rate: The growth rate that will be applied to the dividend every period.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA stock_price: The stock price at period n\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int    \n",
    "    \"\"\"\n",
    "    \n",
    "    # initalize our total cashflows\n",
    "    total_cashflows = 0\n",
    "    \n",
    "    # loop the number of periods and calculate the cash flows.\n",
    "    for period in range(1, periods + 1):\n",
    "        \n",
    "        # define the growth and discount factor\n",
    "        growth_factor = (1 + growth_rate)\n",
    "        discount_factor = (1 + discount_rate) ** period\n",
    "        \n",
    "        # calculate the cashflow\n",
    "        cashflow = (dividends * growth_factor) ** period / discount_factor\n",
    "        total_cashflows = total_cashflows + cashflow\n",
    "    \n",
    "    # calculate the terminal value, or the stock price at period n.\n",
    "    terminal_val =  stock_price / (1 + discount_rate) ** periods \n",
    "\n",
    "    return total_cashflows + terminal_val\n",
    "    \n",
    "\n",
    "#EXAMPLE\n",
    "disc_rate = 0.132\n",
    "grow_rate = 0.05\n",
    "dividends = 1.0\n",
    "stock_price = 14.12\n",
    "periods = 5\n",
    "\n",
    "divident_discount_model(disc_rate, dividends, grow_rate, stock_price, periods)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Gordon Growth Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "30.000000000000004"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def gordon_growth_model(dividend, dividend_growth_rate, required_rate_of_return):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the value of a stock using a Gordon Growth model.\n",
    "    \n",
    "    PARA dividend: The dividend earned over the life of the stock.\n",
    "    PARA type: float\n",
    "\n",
    "    PARA dividend_growth_rate: The growth rate in the value of the dividend every period.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA required_rate_of_return: The required rate of return for the investor.\n",
    "    PARA type: float\n",
    "   \n",
    "    \"\"\"  \n",
    "    \n",
    "    dividend_period_one = dividend * (1 + dividend_growth_rate)\n",
    "    \n",
    "    return dividend_period_one / (required_rate_of_return - dividend_growth_rate)\n",
    "\n",
    "div = 2.00\n",
    "gro = 0.05\n",
    "rrr = 0.12\n",
    "\n",
    "gordon_growth_model(div, gro, rrr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multi Stage Growth Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "34.737791134485335"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def multistage_growth_model(dividend, discount_rate, growth_rate, constant_growth_rate, periods):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the value of a stock using a multistage growth model.\n",
    "    \n",
    "    PARA dividend: The dividend earned over the life of the stock.\n",
    "    PARA type: float\n",
    "\n",
    "    PARA discount_rate: The discount rate used to calculate the NPV & PV calcs.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA growth_rate: The growth rate during the multistage period.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA constant_growth: The growth rate in perpetuity.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA periods: The number of periods.\n",
    "    PARA type: int\n",
    "   \n",
    "    \"\"\"  \n",
    "    total_value= 0\n",
    "  \n",
    "    \n",
    "    for period in range(1, periods + 1):\n",
    "        \n",
    "        # if it's the last period calculate the terminal value\n",
    "        if period == periods:\n",
    "            \n",
    "            # calculate the terminal dividend.\n",
    "            terminal_dividend = (dividend * (1 + growth_rate) ** period)\n",
    "            \n",
    "            # calculate the terminal value and then discount it.\n",
    "            terminal_value = terminal_dividend / (discount_rate - constant_growth_rate)\n",
    "            terminal_value_disc = terminal_value / (1 + discount_rate) ** (period -1)\n",
    "            \n",
    "            # return the total value of the stock\n",
    "            total_value += terminal_value_disc\n",
    "        \n",
    "        # otherwise calculate the cashflow for that period\n",
    "        else:\n",
    "            cashflow = (dividend * (1 + growth_rate) ** period) / (1 + discount_rate) ** period\n",
    "            total_value += cashflow\n",
    "            \n",
    "    return total_value\n",
    "           \n",
    "# EXAMPLE  \n",
    "div = 1.00\n",
    "gro = 0.20\n",
    "cos = 0.05\n",
    "dis = 0.10\n",
    "per = 4\n",
    "\n",
    "multistage_growth_model(div, dis, gro, cos, per)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preferred Stock Valuation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "62.5"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def preferred_stock_valuation(dividend, required_rate_of_return):\n",
    "    \"\"\"\n",
    "    Summary: Given a preferred dividend stock, calculate the value of that stock.\n",
    "    \n",
    "    PARA dividend: The dividend for each period, earned over an infinite period.\n",
    "    PARA type: float\n",
    "\n",
    "    PARA required_rate_of_return: The required rate of return desired for an investment.\n",
    "    PARA type: float\n",
    "    \n",
    "    \"\"\"  \n",
    "    \n",
    "    return dividend / required_rate_of_return\n",
    "\n",
    "# EXAMPLE\n",
    "annual_div = 5.00\n",
    "rrr = .08\n",
    "\n",
    "preferred_stock_valuation(annual_div, rrr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sharpe Ratio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.1970803722581844"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def sharpe_ratio(returns, risk_free_rate):\n",
    "    \"\"\"\n",
    "    Summary: Given an array of returns and a risk-free rate, calculate the Sharpe Ratio.\n",
    "    \n",
    "    PARA returns: A list of returns, for example, daily stock returns.\n",
    "    PARA type: list\n",
    "    \n",
    "    PARA risk_free_rate: The risk-free rate, usually a treasury bill.\n",
    "    PARA type: float\n",
    "    \n",
    "    \"\"\"\n",
    "    \n",
    "    import numpy as np\n",
    "    \n",
    "    returns = np.array(returns)    \n",
    "    \n",
    "    # calculate the avg return and the std return.\n",
    "    avg_return = returns.mean()\n",
    "    std_return = returns.std()\n",
    "    \n",
    "    return (avg_return - risk_free_rate) / std_return\n",
    " \n",
    "# EXAMPLE\n",
    "risk_free_rate = .02\n",
    "returns = [1, 3, 4, 5, 6]\n",
    "sharpe_ratio(returns, risk_free_rate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cost of Preferred Stock"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.08"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def cost_of_preferred_stock(preferred_dividends, market_price_of_preferred):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the cost of preferred stock in the WACC formula.\n",
    "    \n",
    "    PARA preferred_dividends: The amount of a preferred dividend paid in that period.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA market_price_of preferred: The price of a share of preferred stock during the period.\n",
    "    PARA type: float\n",
    "    \n",
    "    \"\"\"    \n",
    "    \n",
    "    return preferred_dividends / market_price_of_preferred\n",
    "\n",
    "\n",
    "# EXAMPLE\n",
    "dividend = 8\n",
    "price = 100\n",
    "cost_of_preferred_stock( dividend, price)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cost of Debt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.048"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def cost_of_debt(interest_rate, tax_rate):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the cost of debt in the WACC formula.\n",
    "    \n",
    "    PARA interest_rate: The interest rate charged on the debt.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA tax_rate: The company's marginal federal plus state tax rate.\n",
    "    PARA type: float\n",
    "    \n",
    "    \"\"\"       \n",
    "    \n",
    "    return interest_rate * (1 - tax_rate)\n",
    "\n",
    "# EXAMPLE\n",
    "interest_rate = .08\n",
    "tax_rate = .4\n",
    "cost_of_debt(interest_rate, tax_rate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cost of Equity - CAPM Method"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.115"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def cost_of_equity_capm(risk_free_rate, market_return, beta):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the cost of equity for WACC using the CAPM method.\n",
    "    \n",
    "    PARA risk_free_rate: The risk-free rate for the market, usually a treasury note.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA market_return: The required rate of return for the company.\n",
    "    PARA type: float\n",
    "\n",
    "    PARA beta: The company's estimated stock beta.\n",
    "    PARA type: float\n",
    "    \n",
    "    \"\"\" \n",
    "    \n",
    "    return risk_free_rate + (beta * (market_return - risk_free_rate))\n",
    "\n",
    "# EXAMPLE\n",
    "beta = 1.1\n",
    "rfr = .06\n",
    "mkt = .11\n",
    "cost_of_equity_capm(rfr, mkt, beta)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cost of Equity - DDM Method"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.11961904761904761"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def cost_of_equity_ddm(stock_price, next_year_dividend, growth_rate):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the cost of equity for WACC using the DMM method.\n",
    "    \n",
    "    PARA stock_price: The company's current price of a share.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA next_year_dividend: The expected dividend to be paid next year.\n",
    "    PARA type: float\n",
    "\n",
    "    PARA growth_rate: Firm's expected constant growth rate.\n",
    "    PARA type: float\n",
    "    \n",
    "    \"\"\"    \n",
    "    return (next_year_dividend / stock_price) + growth_rate\n",
    "\n",
    "# EXAMPLE\n",
    "p = 21\n",
    "d = 1\n",
    "g = .072\n",
    "cost_of_equity_ddm(p, d, g)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cost of Equity - Risk Premium Method"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.13"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def cost_of_equity_bond(bond_yield, risk_premium):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the cost of equity for WACC using the Bond yield plus risk premium method.\n",
    "    \n",
    "    PARA bond_yield: The company's interest rate on long-term debt.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA risk_premium: The company's risk premium usually 3% to 5%.\n",
    "    PARA type: float\n",
    "    \n",
    "    \"\"\"   \n",
    "    return bond_yield + risk_premium\n",
    "\n",
    "# EXAMPLE\n",
    "y = .08\n",
    "p = .05\n",
    "cost_of_equity_bond(y, p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Capital Weights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def capital_weights(preferred_stock, total_debt, common_stock):\n",
    "    \"\"\"\n",
    "    Summary: Given a firm's capital structure, calculate the weights of each group.\n",
    "    \n",
    "    PARA total_capital: The company's total capital.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA preferred_stock: The company's preferred stock outstanding.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA common_stock: The company's common stock outstanding.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA total_debt: The company's total debt.\n",
    "    PARA type: float\n",
    "    \n",
    "    RTYP weights_dict: A dictionary of all the weights. \n",
    "    RTYP weights_dict: dictionary\n",
    "    \n",
    "    \"\"\"      \n",
    "    # initalize the dictionary\n",
    "    weights_dict = {}\n",
    "    \n",
    "    # calculate the total capital\n",
    "    total_capital = preferred_stock + common_stock + total_debt\n",
    "    \n",
    "    # calculate each weight and store it in the dictionary\n",
    "    weights_dict['preferred_stock'] = preferred_stock / total_capital\n",
    "    weights_dict['common_stock'] = common_stock / total_capital\n",
    "    weights_dict['total_debt'] = total_debt / total_capital\n",
    "    \n",
    "    return weights_dict\n",
    "\n",
    "# EXAMPLE\n",
    "debt = 8000000\n",
    "preferred_stock = 2000000\n",
    "common_stock = 10000000\n",
    "capital_weights(preferred_stock, debt, common_stock)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Weighted Average Cost of Capital"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0922"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def weighted_average_cost_of_capital(cost_of_common, cost_of_debt, cost_of_preferred, weights_dict):\n",
    "    \"\"\"\n",
    "    Summary: Calculate a firm's WACC.\n",
    "    \n",
    "    PARA cost_of_common: The firm's cost of common equity.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA cost_of_debt: The firm's cost of debt.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA cost_of_preferred: The firm's cost of preferred equity.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA weights_dict: The capital weights for each capital structure.\n",
    "    PARA type: dictionary\n",
    "    \n",
    "    \"\"\"    \n",
    "    \n",
    "    weight_debt = weights_dict['total_debt']\n",
    "    weight_common = weights_dict['common_stock']\n",
    "    weight_preferred = weights_dict['preferred_stock']\n",
    "    \n",
    "    return (weight_debt * cost_of_debt) + \n",
    "           (weight_common * cost_of_common) + \n",
    "           (weight_preferred * cost_of_preferred)\n",
    "\n",
    "# Cost of Equity\n",
    "y = .08\n",
    "p = .05\n",
    "ke = cost_of_equity_bond(y, p)\n",
    "\n",
    "# Cost of Debt\n",
    "interest_rate = .08\n",
    "tax_rate = .4\n",
    "kd = cost_of_debt(interest_rate, tax_rate)\n",
    "\n",
    "# Cost of Preferred\n",
    "dividend = 8\n",
    "price = 100\n",
    "kp = cost_of_preferred_stock( dividend, price)\n",
    "\n",
    "# Capital Weights\n",
    "debt = 8000000\n",
    "preferred_stock = 2000000\n",
    "common_stock = 10000000\n",
    "weights = capital_weights(preferred_stock, debt, common_stock)\n",
    "\n",
    "weighted_average_cost_of_capital(ke, kd, kp, weights)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Asset Beta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.4390243902439025"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def asset_beta(tax_rate, equity_beta, debt_to_equity):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the asset beta for a publicly traded firm.\n",
    "    \n",
    "    PARA tax_rate: A comparable publicly traded company's marginal tax rate.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA equity_beta: A comparable publicly traded company's equity beta.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA debt_to_equity: A comparable publicly traded company's debt-to-equity ratio.\n",
    "    PARA type: float\n",
    "        \n",
    "    \"\"\"     \n",
    "    \n",
    "    return equity_beta * 1 / (1 + ((1 - tax_rate) * debt_to_equity))\n",
    "\n",
    "#EXAMPLE\n",
    "tax_rate = .3\n",
    "equity_beta = .9\n",
    "dte = 1.5   \n",
    "                          \n",
    "asset_beta(tax_rate, equity_beta, dte)                "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Project Beta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9658536585365856"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def project_beta(tax_rate, asset_beta, debt_to_equity):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the project beta for the subject firm.\n",
    "    \n",
    "    PARA tax_rate: Company's marginal tax-rate.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA asset_beta: A comparable publicly traded company's asset beta.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA debt_to_equity: Company's debt-to-equity ratio.\n",
    "    PARA type: float\n",
    "        \n",
    "    \"\"\"     \n",
    "    \n",
    "    return asset_beta * (1 + ((1 - tax_rate)*debt_to_equity))\n",
    "\n",
    "#Example\n",
    "a = asset_beta(.3, .9, 1.5)   \n",
    "t = .4\n",
    "d = 2\n",
    "project_beta(t, a,d )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Degree of Operating Leverage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.6666666666666667"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def degree_of_operating_leverage(quantity, variable_cost, price, fixed_cost):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the degree of operating leverage.\n",
    "    \n",
    "    PARA quantity: Quantity of units sold.\n",
    "    PARA type: int\n",
    "    \n",
    "    PARA variable_cost: The variable cost per unit.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA fixed_cost: Total fixed costs\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA price: The price per unit.\n",
    "    PARA type: float\n",
    "        \n",
    "    \"\"\"        \n",
    "    \n",
    "    return (quantity * (price - variable_cost)) /  (quantity * (price - variable_cost) - fixed_cost)\n",
    "\n",
    "price = 4.00\n",
    "variable = 3.00\n",
    "quantity = 100000\n",
    "fixed = 40000\n",
    "\n",
    "degree_of_operating_leverage(quantity, variable, price, fixed) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Degree of Financial Leverage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.4285714285714286"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def degree_of_financial_leverage(ebit, interest):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the degree of operating leverage.\n",
    "    \n",
    "    PARA ebit: Earnings before interest & taxes.\n",
    "    PARA type: int\n",
    "    \n",
    "    PARA interest: Interest expense per period.\n",
    "    PARA type: float\n",
    "        \n",
    "    \"\"\"  \n",
    "    \n",
    "    return ebit / (ebit - interest)\n",
    "    \n",
    "ebit = 60000\n",
    "interest = 18000\n",
    "\n",
    "degree_of_financial_leverage(ebit, interest)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Degree of Total Leverage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.380952380952381"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def degree_of_total_leverage(financial_leverage, operating_leverage):\n",
    "    \"\"\"\n",
    "    Summary: Calculate the degree of total leverage.\n",
    "    \n",
    "    PARA financial_leverage: Firms degree of financial leverage.\n",
    "    PARA type: float\n",
    "    \n",
    "    PARA operating_leverage: Firms degree of operating leverage.\n",
    "    PARA type: float\n",
    "        \n",
    "    \"\"\"  \n",
    "    \n",
    "    return financial_leverage * operating_leverage\n",
    "\n",
    "fin_lev = degree_of_financial_leverage(60000, 18000)\n",
    "opr_lev = degree_of_operating_leverage(100000, 3.0, 4.0, 40000) \n",
    "degree_of_total_leverage(fin_lev, opr_lev)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
